<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { register } from '@/api/user'

const router = useRouter()

const form = ref({
  name: '',
  username: '',
  password: '',
  confirmPassword: ''
})
const loading = ref(false)
const error = ref('')

const handleRegister = async () => {
  console.log('注册表单数据:', form.value.username)
  if (!form.value.username || !form.value.password || !form.value.confirmPassword) {
    error.value = '请填写所有字段'
    return
  }

  if (form.value.password !== form.value.confirmPassword) {
    error.value = '两次输入的密码不一致'
    return
  }

  loading.value = true
  error.value = ''

  try {
    await register({
      name: form.value.name,
      username: form.value.username,
      password: form.value.password
    })

    router.push('/login')
  } catch (err) {
    console.error('注册失败:', err)
    error.value = '注册失败，请稍后重试'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <h1>注册</h1>
      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <input v-model="form.username" placeholder="用户名" required>
        </div>
        <div class="form-group">
          <input v-model="form.name" placeholder="姓名" required>
        </div>
        <div class="form-group">
          <input v-model="form.password" type="password" placeholder="密码" required>
        </div>
        <div class="form-group">
          <input v-model="form.confirmPassword" type="password" placeholder="确认密码" required>
        </div>
        <button :disabled="loading">
          {{ loading ? '注册中...' : '注册' }}
        </button>
        <p v-if="error" class="error">{{ error }}</p>
        <p class="login-link">
          已有账号？<router-link to="/login">去登录</router-link>
        </p>
      </form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: grid;
  place-items: center;
  min-height: 100vh;
  padding: 1rem;
}

.login-box {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.form-group {
  margin-bottom: 1rem;
}

input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  width: 100%;
  padding: 0.75rem;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.error {
  color: red;
  margin-top: 1rem;
  text-align: center;
}

.login-link {
  margin-top: 1rem;
  text-align: center;
}

.login-link a {
  color: #4CAF50;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style>
